<template>
	<view class="canvas-content">
		<image class="background-image" mode="aspectFill" :src="list[index].background"></image>
		<view class="preview-panel">
			<view class="preview-panel-body"><image @click="showShare = !showShare" :src="list[index].background" mode="aspectFit"></image></view>
			<view class="preview-panel-footer">
				<view class="image-border"><image v-for="(item, index) in list" :src="item.background" @click="selectTemplate(index)" :key="index" mode="aspectFit"></image></view>
			</view>
		</view>
		<loading ref="loading"></loading>
		<canvas class="canvas mp-wx" canvas-id="shareCanvas"></canvas>
	</view>
</template>

<script>
import Loading from '../notice/loading.vue';
import { getWxShareHref } from '../../common/utils.js';
import { list } from './templates.js';
import { authorTodo } from '@/common/utils.js'
console.log(list);
export default {
	components: { Loading },
	data() {
		const info = uni.getSystemInfoSync();
		return {
			ctx: undefined,
			tempFilePath: '',
			showShare: false,
			shareButton: true,
			ratio: info.windowHeight / info.screenHeight,
			scale: 750 / info.windowWidth,
			canvas: {
				width: 750,
				height: 2000
			},
			list,
			index: 0
		};
	},
	props: {
		params: {
			type: Object
		},
		dirayId: {
			type: String
		}
	},
	watch: {
		params: {
			handler(val) {
				if (val && val.title) {
					//通过title判断是否有效
					Object.assign(this.attrs, val);
					this.creatPoster();
				}
			},
			deep: true,
			immediate: true
		}
	},
	mounted() {
		const query = uni.createSelectorQuery().in(this),
			that = this;
		query
			.select('.preview-panel-body')
			.boundingClientRect(rect => {
				that.width = rect.width;
			})
			.exec();
	},
	methods: {
		getImageInfo(src) {
			return uni.getImageInfo({
				src
			});
		},
		async creatPoster() {
			const { attrs, canvas } = this;
			this.masterImage = await this.getImageInfo(attrs.imageUrl);
			this.canvas.height = 600 + (this.masterImage.height * this.canvas.width) / this.masterImage.width;
			this.height = (this.canvas.height * 590) / this.canvas.width;
			this.$refs.loading.show('生成中');
			this.ctx = uni.createCanvasContext('shareCanvas', this);
			this.ctx.draw(); //清空之前的海报
			this.ctx.save();
			// 根据设备屏幕大小和距离屏幕上下左右距离，及圆角绘制背景
			this.roundRect(0, 0, canvas.width, canvas.height, attrs.radius, '#ffffff', [false, false, false, false]);
			this.ctx.restore();
			//绘制标题 top 绘制文本的y位置
			let top = attrs.innerTB;
			await this.createLogo(top);
			top = this.createDate(top);
			//绘制海报图片
			top = await this.createMasterImage(top);
			//绘制摄影师
			top = this.createCameraMan(top);
			// 绘制标题 top 绘制文本的y位置
			top = this.creatTitle(top);
			// 小程序的名称
			top = this.createUserName(top);
			// 绘制小程序码
			await this.createCode(top);

			this.ctx.draw(true, r => {
				this.saveToImage();
			});
		},
		roundRect(x, y, w, h, r, fillColor = '#ffffff', lineStatus = [true, true, true, true]) {
			const { ctx } = this;
			ctx.save();
			ctx.beginPath();
			// 绘制左上角圆弧
			if (lineStatus[0]) {
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
				// 绘制border-top
				ctx.lineTo(x + w - r, y);
			} else {
				// 绘制border-top
				ctx.lineTo(x + w - r, y);
			}
			// 绘制右上角圆弧
			if (lineStatus[1]) {
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
				// 绘制border-right
				ctx.lineTo(x + w, y + h - r);
			} else {
				// 不全border-top
				ctx.lineTo(x + w, y);
				// 绘制border-right
				ctx.lineTo(x + w, y + h - r);
			}
			// 绘制右下角圆弧
			if (lineStatus[2]) {
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
				// 绘制border-bottom
				ctx.lineTo(x + r, y + h);
			} else {
				// 不全border-right
				ctx.lineTo(x + w, y + h);
				// 绘制border-bottom
				ctx.lineTo(x, y + h);
			}

			// 绘制左下角圆弧
			if (lineStatus[3]) {
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
				// 绘制border-left
				ctx.lineTo(x, y + r);
			} else {
				// 不全border-right
				ctx.lineTo(x, y + h);
				// 绘制border-bottom
				ctx.lineTo(x, y);
			}
			// 填充颜色
			ctx.setFillStyle(fillColor);
			ctx.fill();
			// 剪切，剪切之后的绘画绘制剪切区域内进行，需要save与restore 这个很重要 不然没办法保存
			ctx.clip();
			ctx.restore();
		},

		createMasterImage(top) {
			top += 47;
			const { ctx, attrs, canvas } = this;
			let width = canvas.width;
			let height = (this.masterImage.height * width) / this.masterImage.width;
			ctx.save();
			ctx.drawImage(this.masterImage.base64, 0, 0, this.masterImage.width, this.masterImage.height, 0, top, width, height);
			ctx.restore();
			return height + top;
		},
		async createCode(textY) {
			const { ctx, attrs, canvas } = this;
			if (!attrs.codeUrl) {
				return;
			}
			const info = await this.getImageInfo(attrs.codeUrl);
			if (info) {
				ctx.save();
				ctx.drawImage(info.base64, 0, 0, info.width, info.height, (canvas.width - 118) / 2, textY + 48, 118, 118);
				ctx.restore();
			}
		},
		createUserName({ text = '', left = 0, top = 0, color = '#66645D', size = 24 }) {
			const { ctx, attrs, canvas } = this;
			ctx.save();
			ctx.setFontSize(size);
			ctx.setFillStyle(color);
			ctx.fillText(text, left, top);
			ctx.restore();
		},
		drawText({ text, left, top, lineHeight = 46, maxWidth, textAlign = 'left', color = '#65645D' }) {
			const { ctx, canvas, attrs } = this;
			maxWidth = maxWidth || canvas.width;
			ctx.setFillStyle(color);
			// 设置垂直对齐方式
			let arrText = text.split('');
			let line = '';
			for (let i = 0; i < arrText.length; i++) {
				let textLine = line + arrText[i];
				let metrics = ctx.measureText(textLine);
				if (metrics.width > maxWidth && i > 0) {
					ctx.fillText(line, left, top);
					line = arrText[i];
					top += lineHeight;
				} else {
					line = textLine;
				}
			}

			if (textAlign === 'left') {
				ctx.fillText(line, left, top);
			} else if (textAlign === 'center') {
				ctx.textAlign = textAlign;
				ctx.fillText(line, canvas.width / 2, top);
			}
			return top;
		},
		saveToImage() {
			const { canvas } = this;
			// 把画布转化成临时文件
			uni.canvasToTempFilePath(
				{
					x: 0,
					y: 0,
					width: canvas.width, // 画布的宽
					height: canvas.height + this.textHeight, // 画布的高
					canvasId: 'shareCanvas',
					fileType: 'png',
					success: async res => {
						this.tempFilePath = res.tempFilePath;
						this.$refs.loading.hide();
						this.shareButton = false;
					},
					fail: res => {
						uni.showToast({
							title: '保存失败，稍后再试',
							duration: 2000,
							icon: 'none'
						});
						this.$refs.loading.hide();
					}
				},
				this
			);
		},
		downloadSharePhoto() {
			// 保存图片至相册
			this.shareDirayAdd();
			authorTodo({
				type: 'writePhotosAlbum',
				reject: () => {
					this.$refs.loading.hide();
				},
				success: () => {
					this.$refs.loading.show('保存中');
					uni.saveImageToPhotosAlbum({
						filePath: this.tempFilePath,
						success: res => {
							this.$refs.loading.hide();
							this.showShare = false;
							uni.showToast({
								title: '保存成功，可以去分享啦~',
								duration: 2000,
								icon: 'none'
							});
						},
						fail: () => {
							console.log('保存失败，稍后再试');
							this.$refs.loading.hide();
						}
					});
				}
			})
		},
		close() {
			this.$refs.loading.hide();
			this.$emit('close');
		},
		selectTemplate(index){
			this.index = index;
		}
	}
};
</script>

<style lang="less" scoped>
/* 按钮去掉边框 */
button::after {
	border: none;
}
button {
	color: #66645d;
}

.canvas-content {
	.canvas {
		width: 750px;
		height: 2000px;
		&.mp-wx {
			position: fixed;
			top: 300%;
		}
	}

	.background-image {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
		filter: blur(6px) opacity(0.5) brightness(0.95);
	}

	.preview-panel {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		.preview-panel-body {
			flex-grow: 1;
			image {
				width: 630rpx;
				height: 1050rpx;
				vertical-align: middle;
				box-shadow: 0 4rpx 20rpx 0 rgba(102, 100, 93, 0.1);
				border-radius: 20rpx;
				margin: 28rpx 60rpx 0 60rpx;
			}
		}
		.preview-panel-footer {
			flex-shrink: 0;
			margin: 28rpx;
			overflow-x: auto;
			.image-border {
				width: calc(123rpx * 6 + 180rpx);
				image {
					width: 123rpx;
					height: 205rpx;
					margin: 0 18rpx;
					border-radius: 10rpx;
					&:first-child {
						margin-left: 0;
					}
					&:last-child {
						margin-right: 0;
					}
				}
			}
		}
	}
}
</style>
